import os
from data.base_dataset import BaseDataset, get_transform
from data.image_folder import make_dataset, get_affine_transform
from PIL import Image
import random
import numpy as np
import torch
import cv2
import matplotlib.pyplot as plt
from torchvision import transforms

class UnalignedDataset(BaseDataset):
    """
    This dataset class can load unaligned/unpaired datasets.

    It requires two directories to host training images from domain A '/path/to/data/trainA'
    and from domain B '/path/to/data/trainB' respectively.
    You can train the model with the dataset flag '--dataroot /path/to/data'.
    Similarly, you need to prepare two directories:
    '/path/to/data/testA' and '/path/to/data/testB' during test time.
    """

    def __init__(self, opt):
        """Initialize this dataset class.

        Parameters:
            opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
        """
        BaseDataset.__init__(self, opt)
        self.dir_A = os.path.join(opt.dataroot, opt.phase + 'A')  # create a path '/path/to/data/trainA'
        self.dir_B = os.path.join(opt.dataroot, opt.phase + 'B')  # create a path '/path/to/data/trainB'

        self.A_paths = sorted(make_dataset(self.dir_A, opt.max_dataset_size))   # load images from '/path/to/data/trainA'
        self.B_paths = sorted(make_dataset(self.dir_B, opt.max_dataset_size))    # load images from '/path/to/data/trainB'
        self.A_size = len(self.A_paths)  # get the size of dataset A
        self.B_size = len(self.B_paths)  # get the size of dataset B
        btoA = self.opt.direction == 'BtoA'
        input_nc = self.opt.output_nc if btoA else self.opt.input_nc       # get the number of channels of input image
        output_nc = self.opt.input_nc if btoA else self.opt.output_nc      # get the number of channels of output image
        self.transform_A = get_transform(self.opt, grayscale=(input_nc == 1))
        self.transform_B = get_transform(self.opt, grayscale=(output_nc == 1))

    def __getitem__(self, index):
        """Return a data point and its metadata information.

        Parameters:
            index (int)      -- a random integer for data indexing

        Returns a dictionary that contains A, B, A_paths and B_paths
            A (tensor)       -- an image in the input domain
            B (tensor)       -- its corresponding image in the target domain
            A_paths (str)    -- image paths
            B_paths (str)    -- image paths
        """
        A_path = self.A_paths[index % self.A_size]  # make sure index is within then range
        if self.opt.serial_batches:   # make sure index is within then range
            index_B = index % self.B_size
        else:   # randomize the index for domain B to avoid fixed pairs.
            index_B = random.randint(0, self.B_size - 1)
        B_path = self.B_paths[index_B]
        A_img = Image.open(A_path).convert('RGB')
        A = self.transform_A(A_img)
        # B_img = Image.open(B_path).convert('RGB')
        # apply image transformation
        # B = self.transform_B(B_img)

        # the img B may performs different: 
        tmpB = np.load(B_path) # HWC(D RGB RGB)
        tmpB[:,:,3] = tmpB[:,:,3]*255
        tmpA = np.array(A_img)

        sf = 0.1 # 0.9-1.1
        rf = 10 # 10*2

        s = np.array([1,1])
        s = s * np.clip(np.random.randn()*sf + 1, 1 - sf, 1 + sf)
        c = np.array([111.5,111.5])
        r = np.clip(np.random.randn()*rf, -rf*2, rf*2) \
            if random.random() <= 0.4 else 0

        is_flip = True # for random flip

        if is_flip and random.random() <= 0.5:
            tmpB = tmpB[:, ::-1, :]
            tmpA = tmpA[:, ::-1, :]

        shift=np.array([random.random()/10, random.random()/10], dtype=np.float32) if random.random() <= 0.4 else np.array([0, 0], dtype=np.float32)
        # print("the shift is ", shift)
        image_size = (256,256)
        trans = get_affine_transform(c, s, r, image_size,shift=shift)
        B = cv2.warpAffine(
            tmpB,
            trans,
            (int(image_size[0]), int(image_size[1])),
            flags=cv2.INTER_LINEAR)
        A = cv2.warpAffine(
            tmpA,
            trans,
            (int(image_size[0]), int(image_size[1])),
            flags=cv2.INTER_LINEAR)
        
        A = torch.from_numpy(A.transpose(2, 0, 1))/255.
        B = torch.from_numpy(B.transpose(2, 0, 1))/255.

        data_transformA = transforms.Compose([transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
        data_transformB = transforms.Compose([transforms.Normalize((0.5, 0.5, 0.5, 0.5, 0.5, 0.5,0.5), \
            (0.5, 0.5, 0.5, 0.5, 0.5, 0.5,0.5))])
        A = data_transformA(A).float()
        B = data_transformB(B).float()

        return {'A': A, 'B': B, 'A_paths': A_path, 'B_paths': B_path}

    def __len__(self):
        """Return the total number of images in the dataset.

        As we have two datasets with potentially different number of images,
        we take a maximum of
        """
        return max(self.A_size, self.B_size)
